package com.usermanage.controller;

import com.usermanage.util.*;
import kingdee.bos.webapi.client.K3CloudApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/kingDee")
public class KindeeController {


    @RequestMapping(value = "/materialInventory/list.json")
    public JsonData inventoryList(String key, Integer page, Integer size) throws Exception {
        K3CloudApiClient client = KingDeeUtil.login(StaticUtil.DATASOURCE);
        String fieldKeys = "FMaterialId.FNumber,FMaterialName,FStockName,FStockUnitId.FName,FBaseQty,FBaseAVBQty,FStockStatusId.FName,FStockOrgId.FName,FStoreurNum,FStoreurNom,FBaseUnitId.FPrecision";
        StringBuffer buffer = new StringBuffer();
        buffer.append("FStockName = '").append("成品仓").append("' and ");
        buffer.append("(FMaterialId.FNumber like '%").append(key).append("%' or ");
        buffer.append("FMaterialName like '%").append(key).append("%' or ");
        buffer.append("FStockUnitId.FName like '%").append(key).append("%' or ");
        buffer.append("FStockStatusId.FName like '%").append(key).append("%' or ");
        buffer.append("FStockOrgId.FName like '%").append(key).append("%' )");
        List<Map> list = KingDeeUtil.query(client, KingdeeStatic.STK_INVENTORY, fieldKeys, buffer.toString(), page, size);
        if (list.size() == 0) {
            return JsonData.successlayertable(null, 0, 0);
        }
        List<Map> result = new ArrayList<>();
        for (Map map : list) {
            Map resultMap = new HashMap();
            resultMap.put("materialId", map.get("FMaterialId.FNumber"));
            resultMap.put("materialName", map.get("FMaterialName"));
            resultMap.put("stockName", map.get("FStockName"));
            resultMap.put("stockUnitName", map.get("FStockUnitId.FName"));
            double fbaseqty = Double.parseDouble(String.valueOf(map.get("FBaseQty")));
            double percent = Double.parseDouble(String.valueOf(map.get("FStoreurNum"))) / Double.parseDouble(String.valueOf(map.get("FStoreurNom")));
            String fqty = StringUtil.formatDecimal(fbaseqty * percent, Integer.valueOf(String.valueOf(map.get("FBaseUnitId.FPrecision"))));
            resultMap.put("fqty", fqty);//库存量（主单位） 基本单位数量 * 基本单位和库存单位的换算率
            resultMap.put("favbqty", fqty);//可用量（主单位）库存量-锁库量          此处锁库量待定
            resultMap.put("stockStatusName", map.get("FStockStatusId.FName"));
            resultMap.put("stockOrgName", map.get("FStockOrgId.FName"));
            result.add(resultMap);
        }
        List<Map> listCount = KingDeeUtil.query(client, KingdeeStatic.STK_INVENTORY, fieldKeys, null, 0, 0);
        return JsonData.successlayertable(result, 0, listCount.size());
    }

}
